package com.lw.easyexcel.test;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.lw.easyexcel.EasyExcelApplication;
import com.lw.easyexcel.mapper.UserMapper;
import com.lw.easyexcel.pojo.User;
import com.lw.easyexcel.service.UserService;
import org.apache.ibatis.session.RowBounds;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * @Description:
 * @ClassName: test
 * @Author: lanwei
 * @Date: 2022/12/14 16:16
 */
@SpringBootTest(classes = EasyExcelApplication.class)
@RunWith(SpringJUnit4ClassRunner.class)
public class test {

    public static final int pageSize = 50000;

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserService userService;

    @Test
    public void test(){
        int i = userMapper.selectCount(new User());
        System.out.println(i);
    }


    @Test
    public void test1(){
        List<User> users = userMapper.selectByRowBounds(new User(), new RowBounds(1, 10));
        users.stream().forEach(u -> System.out.println(u));

    }

    @Test
    public void excelOutPut(){

        String path = "D:\\excel\\人员信息.xls";
        List<User> userByPage = userService.getUserByPage(1);
        ExcelWriter excelWriter = EasyExcel.write(path, User.class).build();
        //sheet
        WriteSheet sheet = EasyExcel.writerSheet(1, "xxxx").build();
        excelWriter.write(userByPage,sheet);
        excelWriter.finish();
        System.out.println("导出成功");
    }


    /**
     * 多sheet页导出
     */
    @Test
    public void excelOutPu2(){
        String path = "D:\\excel\\人员信息.xls";

        final long start = System.currentTimeMillis();

        //获取数据总条数
        int totalCount = userMapper.selectCount(new User());

        ExcelWriter excelWriter = EasyExcel.write(path, User.class).build();

        //需要的sheet页个数
        int sheetNum = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1 ;

        for (int i = 1; i < sheetNum +1 ; i++) {
            List<User> userByPage = userService.getUserByPage(sheetNum);
            //sheet
            WriteSheet sheet = EasyExcel.writerSheet(i, "详细数据【"+(i)+"】").build();
            excelWriter.write(userByPage,sheet);
        }

        excelWriter.finish();
        System.out.println("导出成功");
        System.out.println("导出"+ totalCount +"条数据到excel,总花费" + (System.currentTimeMillis() - start) + "ms");
    }


}
